<template>
  <div id="video">
    <div class="btn-group">
      <input type="number" max="1.0" min="0.0" step="0.01" v-model="visible">
      <button @click="shot">截图</button>
    </div>
    <GcodeViewer ref="viewer" :url="modelUrl" :visible="visible" :opts="option" :onProgress="onProgress" />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import GcodeViewer from "./GcodeViewer/index.vue";
import requests from './requests.js'

// https://storage.googleapis.com/ucloud-v3/61575ddb9d8a176950431398.gcode
// http://172.23.211.82:7001/pfiles/1068339.gcode
// https://storage.googleapis.com/ucloud-v3/6127a7f9aa32f718b8c1ab4f.gcode

@Component({
  components: {
    GcodeViewer
  }
})
export default class HelloWord extends Vue {

  visible = 1.0;

  option = {
    speed: 10,
    quality: 1,
    animation: true,
    layerColor: "#42D4C1",
    topLayerColor: "#E0B12D",
    gridHelper: false,
    lightHelper: true,
    axesHelper: true
  }

  modelUrl = "https://storage.googleapis.com/ucloud-v3/61575ddb9d8a176950431398.gcode";

  progress = {};

  onProgress(progress: any) {
    this.progress = progress
    // console.log(progress);
  }

  onFinished(progress: any) {
    console.log(progress);
  }

  shot(){
    const viewer:any = this.$refs.viewer;
    var image:any = viewer.canvas2image()
    // this.downloadCanvasPicture()
    // var aDom = document.createElement("a"); // 创建一个 a 标签
    // aDom.download = "canvas"; // 设置文件名
    // aDom.href = image; // 放入href
    // document.body.appendChild(aDom); // 将a标签插入 body
    // aDom.click(); // 触发 a 标签的点击
    // document.body.removeChild(aDom); // 移除刚才插入的 a 标签

    requests.qtQuest({
      method: "saveCanvas",
      params: {
        base64: image,
        modelInfo:this.progress
      }
    })
  }
  // 下载canvas截图到本地
  downloadCanvasPicture(): void {
    /******第一步：将canvas内容保存为base64******/
    var cv: any = document.getElementById("canvas");
    var url = cv.toDataURL("image/png");
    
    /******第二步：将base64转换为文件对象******/
    var arr = url.split(","),
      mime = arr[0].match(/:(.*?);/)[1], // 此处得到的为文件类型
      bstr = atob(arr[1]), // 此处将base64解码
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) { u8arr[n] = bstr.charCodeAt(n); }
    var file = new File([u8arr], `canvas.png`, { type: mime });   // 将以上变量生成文件对象，三个参数分别为文件内容、文件名、文件类型
    
    /******第三步：将文件对象通过a标签下载********/
    var aDom = document.createElement("a"); // 创建一个 a 标签
    aDom.download = file.name; // 设置文件名
    var href = URL.createObjectURL(file); // 将file对象转成 UTF-16 字符串
    aDom.href = href; // 放入href
    document.body.appendChild(aDom); // 将a标签插入 body
    aDom.click(); // 触发 a 标签的点击
    document.body.removeChild(aDom); // 移除刚才插入的 a 标签
    URL.revokeObjectURL(href); // 释放刚才生成的 UTF-16 字符串
  }
}
</script>

<style scoped>
.btn-group {
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
}

button {
  position: relative;
  top: 1px; left: 1px;
}
</style>
